<?php
/**
 * 如花拼团开源系统 -- 永久免费
 * =========================================================
 * 官方网址：http://www.phps.shop
 * 作者：光爵【API + 后台】 、 小草【小程序 + WAP】
 * QQ 交流群：728615087
 * Version：1.0.0
 */

namespace app\api\model;

use app\lib\exception\BaseException;
use app\lib\exception\SuccessMessage;
use think\model\concern\SoftDelete;
use think\Db;

class Image extends BaseModel
{
    use SoftDelete;
    protected $hidden = ['update_time','create_time'];
    protected $deleteTime = 'delete_time';

    //创建用户地址
    public static function CreateOne($uid,$post)
    {
        $Image=new Image;
        Db::startTrans();
        try {
            $post['user_id'] = $uid;
            $result = $Image->where(['user_id'=>$uid,'type'=>$post['type'],'img_type'=>$post['img_type']])->select();
            $res  = (!empty($post['id']) && $result) ? true : false;
            $Image->isUpdate($res)->save($post); //直接通过关联模型来新增
            Db::commit();
        }catch (\Exception $e) {
            Db::rollback();// 回滚事务
            throw new BaseException(['msg'=>'上传图片失败']);
        }
        return json(new SuccessMessage(), 201);
    }

    //获取初始签证信息
    public static function GetInfo($uid,$post){
        $Image = new Image;
        $result = '';
        $data = $Image->where(['user_id'=>$uid,'img_type'=>$post['img_type']])->select();
        foreach ($data->toArray() as &$value)
            $result[$value['type']] = $value;
        $result = json_encode($result);
        unset($data);
        return $result;
    }

    //删除对应图片
    public static function image_all_del($uid='',$img_type=''){
        $res = Image::where(['user_id'=>$uid,'img_type'=>$img_type])->field('id')->select();
        if(!$res->isEmpty()){
            Db::startTrans();
            try {
                foreach ($res->toArray() as $key => &$value)
                    $ids[] = $value['id'];
                Image::destroy($ids);
                Db::commit();
            }catch (\Exception $e) {
                Db::rollback();// 回滚事务
                throw new BaseException(['msg'=>'批量删除错误']);
            }
        }
        return json(new SuccessMessage(),201);
    }
}